package org.jsola.hr.web;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.handler.CellWriteHandler;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsola.common.FileKit;
import org.jsola.core.Page;
import org.jsola.core.Result;
import org.jsola.exception.ParamException;
import org.jsola.hr.common.ExcelKit;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dto.*;
import org.jsola.hr.dto.excel.GysInfoImportDTO;
import org.jsola.hr.exception.HrException;
import org.jsola.hr.query.GysInfoQuery;
import org.jsola.hr.service.IGysInfoService;
import org.jsola.hr.vo.FormGroupVO;
import org.jsola.hr.vo.GysInfoListVO;
import org.jsola.hr.vo.GysInfoVO;
import org.jsola.hr.vo.HeaderVo;
import org.jsola.hr.vo.excel.GysInfoExportVO;
import org.jsola.hr.vo.excel.ParseResultVO;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;


/**
 * 供应商信息表
 *
 * @author zhr
 */
@RestController("hrGysInfoController")
@RequestMapping(HrConstants.API_PATH + "/v1/gysInfos")
public class GysInfoController implements IGysInfoControllerAPI {

    @Autowired
    private IGysInfoService gysInfoService;

    @Override
    @PostMapping
    public Result<GysInfoVO> save(@Valid @RequestBody GysInfoAddDTO gysInfoAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增供应商信息表权限校验

        return Result.success(
                gysInfoService.save(gysInfoAddDTO, tokenUser)
        );
    }

    @Override
    @PostMapping("/saveGsyInfo")
    public Result<GysInfoVO> saveGsyInfo(@Valid @RequestBody GysAddDTO gysAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增供应商信息表权限校验

        if (tokenUser == null) {
            if (StringUtils.isBlank(gysAddDTO.getSiteId())) {
                throw new ParamException("租户id不能为空");
            }
            tokenUser = new TokenUser();
            tokenUser.setSiteId(gysAddDTO.getSiteId());
            tokenUser.setUserId("h5");
        }

        return Result.success(
                gysInfoService.saveGsyInfo(gysAddDTO, tokenUser)
        );
    }

    @Override
    @PutMapping("/updateGsyInfo")
    public Result<Integer> updateGsyInfo(@Valid @RequestBody GysUpdateDTO gysUpdateDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增供应商信息表权限校验
        int count = gysInfoService.updateGsyInfo(gysUpdateDTO, tokenUser);
        if (count == 0) {
            throw new ParamException("更新失败，请刷新页面后重试");
        }
        return Result.success(count);
    }


    @Override
    @PutMapping
    public Result<Integer> update(@Valid @RequestBody GysInfoUpdateDTO gysInfoUpdateDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改供应商信息表权限校验

        int count = gysInfoService.update(gysInfoUpdateDTO, tokenUser);
        if (count == 0) {
            throw new ParamException("更新失败，请刷新页面后重试");
        }
        return Result.success(count);
    }


    @Override
    @PostMapping(value = "/batch")
    public Result batch(@Valid @RequestBody GysInfoBatchDTO gysInfoBatchDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量操作权限校验

        // 批量操作，注意校验，有越权风险
        // 新增
        List<GysInfoAddDTO> gysInfoAddDTOList = gysInfoBatchDTO.getGysInfoAddDTOList();
        if (!CollectionUtils.isEmpty(gysInfoAddDTOList)) {
            gysInfoService.batchSave(gysInfoAddDTOList,tokenUser);
        }
        // 修改
        List<GysInfoUpdateDTO> gysInfoUpdateDTOList = gysInfoBatchDTO.getGysInfoUpdateDTOList();
        if (!CollectionUtils.isEmpty(gysInfoUpdateDTOList)) {
            gysInfoUpdateDTOList.parallelStream().forEach(
                    gysInfoUpdateDTO -> {
                        gysInfoService.update(gysInfoUpdateDTO,tokenUser);
                    }
            );
        }
        // 删除
        List<String> deleteGysInfoIdList = gysInfoBatchDTO.getDeleteGysInfoIdList();
        if (!CollectionUtils.isEmpty(deleteGysInfoIdList)) {
            gysInfoService.deleteByIds(tokenUser,deleteGysInfoIdList.toArray(new String[0]));
        }
        return Result.success();
    }


    @Override
    @DeleteMapping(value = "/{gysInfoId}")
    public Result<Integer> delete(@PathVariable String gysInfoId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 彻底删除供应商信息表权限校验

        int count = gysInfoService.deleteByIds(tokenUser, gysInfoId);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @DeleteMapping
    public Result<Integer> deleteBatch(@RequestBody String[] gysInfoIds) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量彻底删除供应商信息表权限校验

        int count = gysInfoService.deleteByIds(tokenUser, gysInfoIds);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @GetMapping(value = "/{gysInfoId}")
    public Result<GysInfoVO> findById(@PathVariable String gysInfoId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看供应商信息表权限校验

        return Result.success(
            gysInfoService.selectById(gysInfoId, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/findGsyById/{gysInfoId}")
    public Result<List<FormGroupVO>> findGsyById(@PathVariable String gysInfoId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看供应商信息表权限校验

        return Result.success(
                gysInfoService.findGsyById(gysInfoId, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/listAll")
    public Result<List<GysInfoListVO>> listAll(@Valid GysInfoQuery gysInfoQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看供应商信息表权限校验

        return Result.success(
            gysInfoService.select(gysInfoQuery, tokenUser.getSiteId())
        );
    }


    @Override
    @GetMapping
    public Result<Page<GysInfoListVO>> page(@Valid GysInfoQuery gysInfoQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
            gysInfoService.selectPage(gysInfoQuery, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping("/export")
    public ResponseEntity<Resource> export(@Valid GysInfoQuery gysInfoQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 导出权限校验

        HeaderVo headerVo = gysInfoService.head(tokenUser);
        String excelUrl = ExcelKit.exportExcelDynamic( "员工列表",
                headerVo.getHead(),
                gysInfoService.allFieldValue(gysInfoQuery, headerVo.getEnNameHeader(), tokenUser.getSiteId())
        );

        // 编码文件名，防止乱码
        String filenames = new String(FilenameUtils.getName(excelUrl).getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + filenames + "\"")
                .header(HttpHeaders.CONTENT_TYPE,"application/vnd.ms-excel")
                .body(new FileSystemResource(excelUrl));
    }

    @Override
    @PostMapping("/parse")
    public Result<List<ParseResultVO<GysInfoImportDTO>>> parseImportFile(@RequestParam("file") MultipartFile file, @RequestParam(required = false) Boolean success) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 导入解析excel权限校验

        // 临时保存到本地
        String excelFilePath = FileKit.saveFileToLocal(file,null,null,new String[]{"xls","xlsx"},null);
        File excelFile = new File(excelFilePath);
        HrException.isTrue(excelFile.exists(), "文件上传失败");
        return Result.success(
                gysInfoService.parseImportFile(excelFile, success, tokenUser)
        );
    }

    @Override
    @PostMapping("/import")
    public Result<Integer> importFile(@RequestParam("file") MultipartFile file, @RequestParam(required = false) Boolean force) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 导入excel权限校验

        // 临时保存到本地
        String excelFilePath = FileKit.saveFileToLocal(file,null,null,new String[]{"xls","xlsx"},null);
        File excelFile = new File(excelFilePath);
        HrException.isTrue(excelFile.exists(), "文件上传失败");
        return Result.success(
                gysInfoService.importFile(excelFile, tokenUser, force)
        );
    }


    @Override
    @GetMapping("/selectPageAllField")
    public Result<Page<Map>> selectPageAllField(@Valid GysInfoQuery gysInfoQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                gysInfoService.selectPageAllField(gysInfoQuery, tokenUser)
        );
    }


}

